<template>
	<view class="back-view" @touchmove.stop.prevent="moveHandle">
		<view class="view-background"></view>
		<view class="white-view-back">
			<view class="top-back">
				<view class="top-name">{{pageTitle}}</view>
				<view class="close-back" @click="closeBtnAction">
					<image class="close-img" src="../../../static/close.png"></image>
				</view>
			</view>
			<view class="top-line"></view>
			<scroll-view class="center-back" :scroll-top="commentScrollTop" id="productContainer" scroll-y="true" style="width: 100%;">
				<uni-forms ref="baseForm" :modelValue="baseFormData">
					<uni-forms-item label="商品名称：" labelWidth="100" labelAlign="right" required>
						<view class="item-back-name">
							<uni-easyinput v-model="baseFormData.name" placeholder="请填写" />
						</view>
					</uni-forms-item>
					<uni-forms-item label="商品价格：" labelWidth="100" labelAlign="right" required>
						<view class="item-back2">
							<uni-easyinput type="number" v-model="baseFormData.price" placeholder="请填写" />
							<view class="itwm-back-des">元</view>
						</view>
					</uni-forms-item>
					<uni-forms-item label="商品图片：" labelWidth="100" labelAlign="right" required>
						<uni-file-picker v-model="imgArr" :image-styles="imageStyles" limit="1"
							file-extname='jpeg,png,jpg' fileMediatype="image" @select="selectImg" @delete="deleteImg">
						</uni-file-picker>
						<view class="item-des">只支持JPEG、JPG、PNG格式，建议尺寸1125*1125 px</view>
					</uni-forms-item>
					<uni-forms-item label="服务权益：" labelWidth="100" labelAlign="right" required>
					</uni-forms-item>
					<uni-forms-item label="服务有效期：" labelWidth="200" labelAlign="right" required>
						<view class="item-back1">
							<uni-easyinput type="number" v-model="baseFormData.expireDay" placeholder="请填写" />
							<view class="itwm-back-des">天</view>
						</view>
					</uni-forms-item>
					<uni-forms-item label="可发起总咨询数：" labelWidth="200" labelAlign="right" required>
						<view class="item-back2">
							<uni-easyinput type="number" @input='consultCountChange' v-model="baseFormData.consultCount"
								placeholder="请填写" />
							<view class="itwm-back-des">次</view>
							<uni-data-checkbox multiple v-model="limit" :localdata="limitArr" @change="limitChange">
							</uni-data-checkbox>
						</view>
					</uni-forms-item>
					<uni-forms-item label="限制每：" labelWidth="200" labelAlign="right">
						<view class="item-back">
							<view class="item-back3">
								<uniselect v-model="baseFormData.cycleUnit" :localdata="typeRange" @change="typeChange"
									:clear="false">
								</uniselect>
							</view>
							<view class="itwm-back-des">只可咨询</view>
							<view class="item-back-width">
								<uni-easyinput type='number' v-model="baseFormData.cycleTimes" placeholder="请填写" />
							</view>
							<view class="itwm-back-des">次</view>
						</view>
					</uni-forms-item>
					<uni-forms-item label="可咨询领域：" labelWidth="200" labelAlign="right" required>
						<view class="item-back4">
							<selectxy :zindex=399 selectType='reject' ref="selectxy" :value="multipleArr"
								placeholder="咨询领域" :options="rangeList" @change="multipleChange">
							</selectxy>
						</view>
					</uni-forms-item>
					<uni-forms-item label="商品介绍：" labelWidth="100" labelAlign="right" required>
						<view class="item-back5">
							<myEditor :editorDetail='baseFormData.intro' @getContents="getContents"></myEditor>
						</view>
					</uni-forms-item>
					<uni-forms-item  label="商品状态：" labelWidth="200" labelAlign="right" required>
						<switch color="#2DA9C5" :checked="status" @change.stop="switchChange"
							style="transform:scale(0.7)" />
					</uni-forms-item>
				</uni-forms>
			</scroll-view>
			<view class="bottom-back">
				<view class="bottom-btn bottom-btn-cancel" @click="closeBtnAction">取消</view>
				<view class="bottom-btn" @click="submitAction">保存</view>
			</view>
		</view>
	</view>
</template>

<script>
	import uploadImage from '@/pages/utils/ossutil/uploadFile.js'
	import dataSelect from "@/components/data-select/dataselect.vue"
	import uniselect from "@/packageB/PC/components/uni-data-select/uni-data-select.vue"
	import myEditor from "@/packageB/PC/editor/editor.vue"
	import selectxy from "@/components/select-cy/select-cy.vue"
	import requsetFileId from '@/pages/utils/upload.js'

	export default {
		components: {
			dataSelect,
			uniselect,
			myEditor,
			selectxy
		},

		props: {
			itemID: {
				type: String,
				default: ''
			},
			editType: {
				type: String,
				default: 'add',
			},


			rangeList: {
				type: Array,
				default: [],
			}
		},
		data() {
			return {
				showMask: false,
				pageTitle: "新增商品",
				baseFormData: {
					'id': '',
					'name': '',
					'price': '',
					'picUrls': '',
					'expireDay': '',
					'domainDict': '',
					'consultCount': '',
					'cycleTimes': '',
					'cycleUnit': '',
					'intro': ''
				},
				imgArr: [],
				limit: [],
				limitArr: [{
					text: '无限制',
					value: -1
				}],
				typeRange: [{
						value: '0',
						text: "周"
					},
					{
						value: '1',
						text: "月"
					},
				],

				status: true,
				multipleArr: [],
				selectArr: [],
				imageStyles: {
					width: 120,
					height: 120,
					border: {
						width: 1,
						style: 'dashed',
						radius: '2px'
					}
				},
				commentScrollTop: 10000,
			}
		},

		mounted() {
			if (this.editType == 'edit') {
				this.pageTitle = '编辑商品';
				this.baseFormData.id = this.itemID;
				this.requestInfoData();
			} 
			this.getOss();
			//this.requestDicData();
			this.scrollToTop();
		},
		methods: {
//滚动到底部
			scrollToTop() {
				var _this = this;
				let query = uni.createSelectorQuery().in(_this)
				query.select('#productContainer').boundingClientRect()
				// query.select('#commentContent').boundingClientRect()
				query.exec((res) => {
					console.log(res)
					//如果子元素高度大于父元素高度(显示高度)
					if (res[0].height) {
						//计算出二者差值就是需要滚动的距离
						_this.commentScrollTop = 0;
					}
				})
			},
			submitAction() {
				console.log(this.baseFormData)
				this.requestData()
			},
			//咨询领域
			// async requestDicData() {
			// 	let _this = this
			// 	const res = await this.$myRequest({
			// 		url: "/comm/dict/list/param_consult_domain",
			// 		method: 'GET',
			// 	})
			// 	console.log('返回结果', res)
			// 	if (res.data.code == 200) {
			// 		var arr = [];
			// 		for (var i = 0; i < res.data.data.length; i++) {
			// 			var item = res.data.data[i]
			// 			item.text = item.name;
			// 		}
			// 		_this.rangeList = res.data.data;
			// 		console.log(_this.rangeList)
			// 	}
			// },
			//咨询领域
			multipleChange(item, value) {
				console.log('咨询领域' + item, value);
				this.selectArr = item;
				this.multipleArr = value;
				this.baseFormData.domainDict = value;
			},

			//网络请求示例
			async requestData() {
				var jsInt = /^[0-9]+.?[0-9]*$/; //判断字符串是否为数字
				var jsPosInt = /^[1-9]+[0-9]*]*$/; //判断正整数
				if (!this.baseFormData.name) {
					uni.showToast({
						title: '请填写商品名称',
						icon: 'none'
					})
					return;
				}
				if (!this.baseFormData.price) {
					uni.showToast({
						title: '请填写价格',
						icon: 'none'
					})
					return;
				}
				if (!jsInt.test(this.baseFormData.price)) {
					uni.showToast({
						title: '价格必须为数字',
						icon: 'none'
					})
					return;
				}
				if (!this.baseFormData.picUrls) {
					uni.showToast({
						title: '请选择图片',
						icon: 'none'
					})
					return;
				}
				if (this.limit.length == 0) {
					console.log(this.limit)
					if (!this.baseFormData.consultCount) {
						uni.showToast({
							title: '请填写可咨询数量',
							icon: 'none'
						})
						return;
					}
					if (!jsPosInt.test(this.baseFormData.consultCount)) {
						uni.showToast({
							title: '可咨询数量必须为数字',
							icon: 'none'
						})
						return;
					}
				}

				if (!this.baseFormData.expireDay) {
					uni.showToast({
						title: '请填写有效期',
						icon: 'none'
					})
					return;
				}

				if (!this.baseFormData.intro || this.baseFormData.intro == '<p><br></p>') {
					uni.showToast({
						title: '请填写商品图文介绍',
						icon: 'none'
					})
					return;
				}
				let _this = this
				var dicStr = '';
				for (var i = 0; i < _this.selectArr.length; i++) {

					if (i == 0) {
						dicStr = _this.selectArr[i].value
					} else {
						dicStr += "," + _this.selectArr[i].value
					}
				}
				var parms = {
					'id': this.baseFormData.id,
					'name': this.baseFormData.name,
					'price': parseInt(this.baseFormData.price) * 100,
					'picUrls': this.baseFormData.picUrls,
					'intro': this.baseFormData.intro,
					'expireDay': parseInt(this.baseFormData.expireDay),
					'domainDict': dicStr,
					'consultCount': this.baseFormData.consultCount ? parseInt(this.baseFormData.consultCount) : -1,
					'cycleUnit': this.baseFormData.cycleUnit != '' ? parseInt(this.baseFormData.cycleUnit) : '',
					'cycleTimes': this.baseFormData.cycleTimes ? parseInt(this.baseFormData.cycleTimes) : ''
				}
				console.log(parms)


				var url = "/admin/goods/1";
				if (_this.editType == 'add' && !_this.status) {//禁用
					url = "/admin/goods/0";
				}

				if (_this.editType == 'edit') {
					url = "/admin/goods";
				}
				const res = await this.$myRequest({
					url: url,
					method: _this.editType == 'edit' ? 'PUT' : 'POST',
					data: parms
				})
				console.log('返回结果', res)

				if (res.data.code == 200) {
					uni.showToast({
						title: _this.editType == 'edit' ? '编辑成功' : '添加成功'
					})
					_this.$emit("successBack");
					_this.closeBtnAction()
				}else{
					uni.showToast({
						title: res.data.msg,
						icon: 'none'
					})
				}
			},
			//信息网络请求
			async requestInfoData() {
				let _this = this
				const res = await this.$myRequest({
					url: '/admin/goods/' + this.itemID,
					method: 'GET',
				})
				console.log('返回结果', res)
				if (res.data.code == 200) {
					_this.baseFormData = res.data.data;
					if (_this.baseFormData.consultCount == -1) {
						_this.baseFormData.consultCount = '';
						_this.limit = [-1];
					}
					console.log('都很健康' + _this.baseFormData.cycleUnit)
					if (res.data.data.picUrls) {
						var item = {
							'url': '',
							'fileID': ''
						}
						item.url = _this.$imageUrls({
							picUrls: res.data.data.picUrls,
							height: 400
						})
						item.fileID = _this.$imageUrls({
							picUrls: res.data.data.picUrls,
							height: 400
						})
						_this.imgArr.push(item);

						console.log(_this.imgArr)
					}
					_this.multipleArr = _this.baseFormData.domainDict.split(',');
					for (var i = 0; i < _this.multipleArr.length; i++) {
						var name = _this.multipleArr[0];
						if (name == '-1') {
							name = '不限';
							_this.multipleArr.splice(i, 1, name)
						}

						for (var j = 0; j < _this.rangeList.length; j++) {
							var item = _this.rangeList[j];
							if (item.name == name) {
								_this.selectArr.push(item)
							}
						}
					}

					console.log('是都好几次' + _this.multipleArr);

					_this.$refs.selectxy.likeSuccess(_this.multipleArr, _this.rangeList);
					if (res.data.data.cycleUnit) {
						_this.$set(_this.baseFormData, 'cycleUnit', res.data.data.cycleUnit.code)
					}
					_this.$set(_this.baseFormData, 'price', (res.data.data.price / 100).toFixed(2))
					console.log('数据库' + _this.baseFormData.cycleUnit)
					
					if(_this.baseFormData.status.code == '1'){
						_this.status =true
					}else{
						_this.status =false
					}
				}
			},

			//改变状态
			async switchChange(e) {
				console.log(e)
				this.status = e.detail.value;
			},

			/**
			 * 获取上传文件临时秘钥
			 */
			async getOss() {
				let _this = this
				const res = await _this.$myRequest({
					url: "/comm/oss/sts",
					header: {
						"Authorization": "Basic ZG90Z286ZG90Z28=",
						"token": uni.getStorageSync("accessToken")
					},
				})
				console.log('获取oss上传临时密钥', res)
				if (res.data.code == 200) {
					getApp().globalData.upLoadAccess = res.data.data
					var time = Date.now()
					getApp().globalData.upLoadAccess.time = time
				}
			},

			// 获取上传状态
			async selectImg(res1) {
				var _this = this;
				console.log('选择文件：', res1)
				let uploadPath = res1.tempFiles[0].path;
				let fileSuffixArray = uploadPath.split('.')

				let fileSuffix = res1.tempFiles[0].extname
				let name =  res1.tempFiles[0].name
				let ossPath = 'product'
				const uploads = await requsetFileId.getPath(ossPath, uploadPath, name)
				console.log('uploads', uploads)
				this.baseFormData.picUrls = uploads
				this.baseFormData.targetUrl = uploads;
			},
			//删除图片
			deleteImg() {
				this.baseFormData.picUrls = '';
				this.baseFormData.targetUrl = '';
			},
			//编辑器赋值
			getContents(html) {
				this.baseFormData.intro = html;
				console.log(this.baseFormData.intro)
			},

			startEditAction(e) {
				console.log("开始编写")
				console.log(e)
				this.showMask = true
			},
			//总咨询次数变化
			consultCountChange(e) {
				console.log(e)
				if (e) {
					this.limit = [];
				}
			},

			//限制每
			typeChange(e) {
				console.log(e)
				this.baseFormData.cycleUnit = e;
			},
			//无限制
			limitChange(e) {
				console.log(e)
				if (e.detail.value[0] == -1) {
					this.baseFormData.consultCount = '';
				}
				console.log(this.limit)
			},

			tapMask() {
				this.showMask = false
			},

			closeBtnAction() {
				this.$emit('addBnnerClose')
			},
			moveHandle() {
				return true
			},
		},
	}
</script>

<style scoped>
	.back-view {
		position: fixed;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		z-index: 9;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.view-background {
		position: absolute;
		width: 100%;
		height: 100%;
		z-index: 8;
		background-color: rgba(0, 0, 0, 0.3);
	}

	.white-view-back {
		width: 600px;
		height: 550px;
		padding: 24px;
		max-height: 600px;
		background-color: white;
		margin-top: -20px;
		border-radius: 4px;
		z-index: 10;
		position: absolute;
	}

	.top-back {
		display: flex;
		justify-content: space-between;
	}

	.top-name {
		font-size: 18px;
		font-weight: normal;
		color: #333333;

	}

	.close-back {
		cursor: pointer;
		width: 20px;
		height: 20px;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.close-img {
		width: 12px;
		height: 12px;
	}

	.top-line {
		height: 1px;
		background: #EEEEEE;
		width: 100%;
		margin-top: 20px;
		margin-bottom: 20px;
	}

	/* 
中间高度=总高 600- 20-21 - 20-60 + 14
 */
	.center-back {
		width: 100%;
		max-height: 442px;
		height: 442px;
	}

	.bottom-back {
		bottom: 0px;
		width: 100%;
		display: flex;
		justify-content: flex-end;
		align-items: center;
		position: absolute;
		height: 60px;
		right: 16px;
	}

	.bottom-btn {
		cursor: pointer;
		width: 104px;
		height: 32px;
		background: #2DA9C5;
		border-radius: 2px;
		color: #FFFFFF;
		font-size: 14px;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.bottom-btn-cancel {
		margin-right: 10px;
		background: #FFFFFF;
		border: 1px solid #EEEEEE;
		color: #333333;
	}

	.item-back-name {
		width: 450px;
		align-items: center;
	}

	.item-back {
		width: 450px;
		display: flex;
		align-items: center;
	}

	.item-back1 {
		display: flex;
		width: 100px;
		align-items: center;
	}

	.item-back2 {
		display: flex;
		width: 350px;
		align-items: center;
	}

	.item-back3 {
		width: 100px;
	}

	.item-back4 {
		width: 250px;
	}

	.item-back5 {
		width: 480px;
		border: 1px solid #eee;
		border-radius: 5px;
	}

	.itwm-back-des {
		font-size: 14px;
		margin-left: 8px;
		color: #666666;
		margin-right: 8px;
	}

	.item-back-width {
		width: 80px;
		margin-right: 10px;
	}

	.customer-item {
		display: flex;
		margin-top: 8px;
		align-items: center;

	}

	.customer-back {
		min-width: 168px;
		height: 44px;
		background: #E8F7FB;
		border-radius: 4px;
		display: flex;
		align-items: center;
		margin-right: 10px;
	}

	.customer-img {
		width: 20px;
		height: 20px;
		border-radius: 50%;
		margin-left: 8px;
	}

	.customer-name {
		font-size: 12px;
		font-weight: 400;
		color: #666666;
		margin-left: 2px;
	}

	.customer-phone {
		font-size: 12px;
		font-weight: 400;
		color: #666666;
		margin-left: 4px;
	}

	.customer-close {
		width: 16px;
		height: 16px;
		margin-right: 2px;
		margin-left: auto;
	}

	.customer-item-back {
		display: flex;
		flex-wrap: wrap;

	}

	.selectLaw {
		font-size: 14px;
		border: 1px solid #DCDFE6;
		border-radius: 4px;
		padding: 6px 10px;
		position: relative;
		flex-direction: row;
		align-items: center;
		z-index: 20;
		background-color: white;
	}

	.law-item-back {
		background-color: white;
	}

	.selectLaw-list {
		margin-top: 2px;
		position: absolute;
		width: 445px;
		height: 130px;
		z-index: 22221;
		background-color: white;
		box-shadow: 0px 2px 8px 0px rgba(0, 0, 0, 0.2000);
		border-radius: 2px;
	}

	.mask-view {
		position: absolute;
		width: 100vw;
		height: 100vh;
		z-index: 19;
		background-color: rgba(0, 0, 0, 0.0);
		top: -600px;
		left: 0;
		right: 0;
		bottom: 0;
	}

	.pop-content-back {
		height: 120px;
		margin-left: 20px;
		width: 420px;
		margin-top: 10px;
	}

	.pop-content-list {
		display: flex;
		align-items: center;
		margin-bottom: 10px;
		margin-top: 10px;
	}



	.item-des {
		color: #aaa;
		margin-top: 5px;
		font-size: 12px;
	}
</style>
